import React, { useState, useEffect } from 'react';
import { Tooltip, Select, Row, Col, message, Icon } from 'antd';
import FormItem from '../../../../../../components/FormItem';
import Modal from '../../../../../../components/Modal';
import { IconFont } from '../../../../../../components/IconFont';
import AddDataBase from './addDataBase';
import Detail from '../../../../components/detailCard';
import services from '../../../../../../services/api';

const DataBaseSet = (props) => {
  const { form, value } = props;
  const { getFieldValue, setFieldsValue } = form;
  const [dataBaseList, setDataBaseList] = useState([]);
  const databaseConnectionId = getFieldValue('databaseConnectionId');

  const detailObj = dataBaseList.find((item) => item.id === databaseConnectionId) || {};

  useEffect(() => {
    getDataBaseList();
  }, []);

  useEffect(() => {
    const { databaseName } = detailObj;
    setFieldsValue({ databaseName });
  }, [databaseConnectionId]);

  // 获取数据库列表
  const getDataBaseList = async () => {
    const { data, code } = await services.database.list();
    if (!code) setDataBaseList(data);
  };

  // 数据库
  const handleDatabase = (type) => {
    const dataBaseObj = type ? detailObj : {};
    Modal.open({
      title: '数据库配置',
      width: '600px',
      content: <AddDataBase closeModal={() => Modal.close()} queryList={getDataBaseList} value={dataBaseObj} />,
      isOkBtn: false,
      maskClosable: false,
      isCancelBtn: false,
    });
  };

  const getFormItems = () => {
    const { databaseConnectionId } = value;
    const layout = {
      labelCol: {
        span: 6,
      },
      wrapperCol: {
        span: 18,
      },
    };
    return [
      {
        label: {
          label: '数据库',
          ...layout,
        },
        name: 'databaseConnectionId',
        options: {
          initialValue: databaseConnectionId,
          rules: [
            {
              required: true,
              message: '请选择数据库',
            },
          ],
        },
        component: (
          <Select placeholder='请选择数据库'>
            {dataBaseList.map((item) => (
              <Select.Option value={item.id} key={item.id}>
                {item.databaseName} <span style={{ float: 'right', color: '#999' }}>{item.ipPort}</span>
              </Select.Option>
            ))}
          </Select>
        ),
        after: (
          <Tooltip title='新建数据库连接'>
            <IconFont
              type='iconxitongshezhi'
              style={{
                fontSize: '16px',
                color: '#777',
              }}
              onClick={() => handleDatabase()}
            />
          </Tooltip>
        ),
      },
      {
        label: {},
        name: 'databaseName',
        options: { initialValue: '' },
        component: <></>,
      },
    ];
  };

  const handleDelete = async () => {
    const databaseConnectionId = getFieldValue('databaseConnectionId');
    const { code, msg } = await services.database.delete(databaseConnectionId);
    if (!code) {
      message.success(msg);
      getDataBaseList();
      setFieldsValue({ databaseConnectionId: undefined });
    } else {
      message.error(msg);
    }
  };

  const getDetailList = (data) => [
    {
      label: '数据库名称',
      value: data.databaseName,
      span: 8,
    },
    {
      label: '类型',
      value: data.databaseType,
      span: 8,
    },
    {
      label: '数据库地址',
      value: data.ipPort,
      span: 8,
    },
    {
      label: '用户名',
      value: data.userName,
      span: 8,
    },
    {
      label: '密码',
      value: data.password && data.password.split('').map(() => '*'),
      span: 8,
    },
    {
      label: '备注',
      value: data.remark,
      span: 8,
    },
  ];

  return (
    <div className='database'>
      <Row type='flex'>
        {getFormItems().map((item) => {
          return (
            <Col span={8} key={item.name}>
              <FormItem form={form} item={item} colNum={1} />
            </Col>
          );
        })}
      </Row>
      {!!Object.keys(detailObj).length && (
        <div className='database_detail'>
          <Detail value={getDetailList(detailObj)} />
          <div className='database_detail_operate'>
            <Icon type='edit' onClick={() => handleDatabase('edit')} style={{ fontSize: 16 }} />
            <IconFont type='iconrubbish-gray' onClick={handleDelete} style={{ fontSize: 16 }} />
          </div>
        </div>
      )}
    </div>
  );
};

export default DataBaseSet;
